// pages/discover/addEassy/index.js
const requests = require("../../../utils/request")
import {formatTime} from "../../../utils/util.js"
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    title:"",
    content:'',
    img_url: [],

  },

  input:function(e){
    this.setData({
      content:e.detail.value
    })
  },
  getTitleContent(e)
  {
    this.setData({
      title:e.detail.value
    })
  },

  async _imgCheck(tempFilePath)
  {

  },
  chooseimage()
  {
    var that = this;
    wx.chooseImage({
      count: 9,
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有  original
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
      success:async function(res)
      {
        wx.showLoading({
          title: '图片审核。。。',
        })
        // console.log(res)
        if(res.tempFilePaths.length>0){
          //把每次选择的图push进数组
          //获取之前的图片组
          let img_url = that.data.img_url;
          let alreadyLen = img_url.length
          //每check一个加1，用来判断是否全部检查完
          let checkOverNum=0
          for (let i = 0; i < res.tempFilePaths.length&&i<9-alreadyLen; i++) {
            //做图片审查，审查通过了才能放进数组里
            //获取图片的临时路径
            const tempFilePath = res.tempFilePaths[i]
            let opt= {src:tempFilePath, quality:20}
            wx.compressImage(opt).then(async (res1)=>{//压缩图片
              console.log('压缩图片',res1.tempFilePath)
              let cdnUrl=wx.cloud.CDN({//发送至CDN暂存
                type:'filePath',
                filePath:res1.tempFilePath
              })
              console.log('cdnUrl',cdnUrl)
              let checkRes = await wx.cloud.callFunction({
                name:'imgCheck',
                data:{
                  imgcontent: cdnUrl
                }
              })
              console.log('checkRes',checkRes)
              if(checkRes.result.errCode !=0)
              {
                  //存在违规
                  wx.hideLoading()
                  wx.showModal({
                    title: '违规提示',
                    content: '图片违规',
                    showCancel: false,
                    confirmColor: '#DC143C',
                    success (res) {
                      if (res.confirm) {
                        wx.redirectTo({
                          url: '../index',
                        })
                      }
                    }                    
                  })
              }
              else
              {
                checkOverNum++
                img_url.push(tempFilePath)
                if(checkOverNum==res.tempFilePaths.length)
                {
                  console.log('审查后图片',img_url)
                  wx.hideLoading()
                  if(img_url.length==9)
                  {
                    that.setData({
                      hideAdd:1,
                      img_url: img_url
                    })
                  }else
                  {
                    that.setData({
                      hideAdd: 0,
                      img_url: img_url
                    })
                  }
                }
              }

            })
          
        }
        }
      }
    })
  },
  async send()
  {

    var that = this;
    let contentValid = true
    let imgsValid = true
    const title=this.data.title
    const content= this.data.content
    wx.showLoading({
      title: '正在审核内容。。。',
    })
    //调用云函数进行审核
    let checkRes = await wx.cloud.callFunction({
      name: 'contentCheck' ,
      data:{
        'content': title+content
      } 
    })
      // console.log('审查结果',checkRes)
      wx.hideLoading()
      //获取状态码  0 》》》正常   87014》》》违规
      const {errCode} = checkRes.result
      if(errCode != 0){
        contentValid=false
        // console.log(contentValid)
        wx.showModal({
          title: '违规提示',
          content: '输入的内容违规',
          showCancel: false,
          confirmColor: '#DC143C',
          success (res) {
            if (res.confirm) {
              wx.navigateBack({
                delta: 0,
              })
            }
          }
        })
      }      

    // console.log(contentValid)
      if(contentValid){
          wx.showLoading({
            title: '上传中',
          })

          let uploadImgRes = []
          // console.log(this.data.img_url)
          if(that.data.img_url.length==0)
          {
            await that.addEassy()
            setTimeout(()=>{
              wx.hideLoading()
              wx.navigateBack({
                delta: 0,
              })
            },1000)
          }
          else{
            // console.log(this.data.img_url)
            for(let i=0;i<that.data.img_url.length;i++)
            {
              let item = that.data.img_url[i]
              // console.log(item)
              // let res = await requests.uploadImg(item)
              // console.log(res)
              // uploadImgRes.push(...res)

              let timestamp = (new Date()).valueOf();

              // 将图片上传至云存储空间
            wx.cloud.uploadFile({
              // 指定上传到的云路径
              cloudPath: 'Eassyimgs/'+timestamp + '.png',
              // 指定要上传的文件的小程序临时文件路径
              filePath: item,
              // 成功回调
              success:async res => {
                // console.log('上传成功', res.fileID.split('/'))
                let usefulFileIdArr = res.fileID.split('/')
                let Arrlen = usefulFileIdArr.length
                if (res.fileID) {
                  uploadImgRes.push(usefulFileIdArr[Arrlen-2]+'/'+usefulFileIdArr[Arrlen-1])
                }

                // console.log(uploadImgRes)
                //图片上传完毕
                if(uploadImgRes.length == that.data.img_url.length)
                {
                  console.log('上传完毕')
                  console.log(uploadImgRes)
                  // console.log(app.globalData.imgUrlPre)
                  // let imageUrlArr = uploadImgRes.map((item)=>{
                  //   return app.globalData.imgUrlPre + item
                  // })
                  // console.log(imageUrlArr
                  
                await that.addEassy(uploadImgRes)
                setTimeout(()=>{
                  wx.hideLoading()
                  wx.navigateBack({
                    delta: 0,
                  })
                },1000)
                
                }

              },
              fail:(errCode,errMsg)=>{
                console.log(errCode,errMsg)
              }
            })

            }
          }
        }

  },
  async addEassy(uploadImgRes=[])
  {
    const userId=app.globalData.openid


    requests.communityInterface(undefined,0,this.data.content,uploadImgRes.join(';'),0,formatTime(new Date()),this.data.title,userId,'add').then((res)=>{
       // console.log(res)
       // wx.navigateBack({
       //   delta: 0,
       // })
     },(err)=>{
       console.log(err)
     })
    // let res = await requests.addEassy(undefined,0,this.data.content,uploadImgRes.join(';'),0,formatTime(new Date()),this.data.title,userId)
    // console.log(res)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})